# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.properties import BoundedNumericProperty, StringProperty

from model.gamestate import *

from ui.hat_widget import HatWidget
from ui.settings_field import SettingField

from constants import DEFAULTS, STEPS, BOUNDS, LABELS


class GameConfig(HatWidget):
    PROPS = {}
    AVALIABLE_PROPS = {Phase.QUICK_GAME_SETTINGS: ('time', 'words', 'players'),
                       Phase.GAME_CONFIG: ('time', 'words', 'rounds')}

    def __init__(self, gamestate, presenter, **kwargs):
        """Making display with game settings

        need:
            gamestate.settings(if != None)
        do:
            change settings.time_per_round_sec
            & settings.words_number
        args:
            gamestate: GameState
            presenter: Presenter
        """
        super(GameConfig, self).__init__(presenter, **kwargs)
        self.gamestate = gamestate
        defaults = self.presenter.settings.quick_game
        DEFAULTS['time'] = defaults.def_time_sec
        DEFAULTS['words'] = defaults.def_words_per_player
        DEFAULTS['players'] = defaults.def_players
        if gamestate.settings is not None:
            DEFAULTS['time'] = gamestate.settings.time_per_round_sec
            DEFAULTS['words'] = gamestate.settings.words_number
        prev_widget = None
        for k in self.AVALIABLE_PROPS[self.gamestate.phase]:
            cur = SettingField(DEFAULTS[k], BOUNDS[k][0], BOUNDS[k][1],
                               STEPS[k], _(LABELS[k]), self)
            if prev_widget is not None:
                prev_widget.bind(on_validate=cur.set_focus)
            prev_widget = cur
            self.PROPS[k] = cur
            self.settings_frame.add_widget(cur)
        prev_widget.bind(on_validate=self.next_view)

    def next_view(self, *args):
        """Changes phase to START_GAME

        call on release "Next" button
        """
        self.gamestate.settings = Settings(self.PROPS['words'].prop,
                                           self.PROPS['time'].prop,
                                           self.PROPS['rounds'].prop)
        self.presenter.change_phase(Phase.START_GAME)

    def go_back(self):
        """Changes phase to START_GAME

        call on release "Next" button
        """
        self.gamestate.settings = Settings(self.PROPS['words'].prop,
                                           self.PROPS['time'].prop,
                                           self.PROPS['rounds'].prop)
        self.gamestate.clear()
        self.presenter.change_phase(Phase.WELCOME)
